#hMultiUserSRS SRS configurations for MU-MIMO
#   SRSs = hMultiUserSRS(TDDPATTERN,SPECIALSLOT,CARRIER,NUMLAYERS) creates
#   a multi-user set of SRS configurations, SRSs. TDDPATTERN is the TDD
#   UL-DL pattern. SPECIALSLOT is the special slot configuration. CARRIER
#   is the carrier configuration. NUMLAYERS is a vector containing the
#   number of layers for each user.

function hMultiUserSRS(tddPattern, specialSlot, carrier, numLayers)

    srs = nrSRSConfig()  

    # Configure SRS for widest bandwidth that will fit in the carrier
    CSRS = srs.BandwidthConfigurationTable["C_SRS"]
    mSRS0 = srs.BandwidthConfigurationTable["m_SRS_0"]

    srs.CSRS = CSRS[findlast(mSRS0 .<= carrier[:NSizeGrid])]

     # Schedule SRS in the first special slot of the period, or the first
    # uplink slot if there are no uplink symbols in the special slot    
    slotPeriod = length(tddPattern)
    symD=symG=symU=nothing
    for slotType in ["S", "U"]
        slotOffset = LinearIndices(tddPattern)[findfirst(tddPattern .== slotType)] .- 1
        srs.SRSPeriod = [slotPeriod, slotOffset]
        if slotType == "S"
            s = specialSlot
        else  # slotType == "U"
            s = [0, 0, carrier[:SymbolsPerSlot]]
        end
        symD, symG, symU = s

        if symU != 0
            break
        end
    end

    # Find the lowest KTC value sufficient to configure SRSs for all UEs
    KTCs = [2, 4]
    numUEs = length(numLayers)
    KTC = numUEs / symU
    if KTC > maximum(KTCs)
        error("Insufficient KBarTC and SymbolStart positions for the configured number of UEs.")
    else
        srs.KTC = KTCs[findfirst(KTCs .>= KTC)]
    end

    # Create an array of SRS configurations, one for each UE, and
    # configure the number of ports, OFDM symbol number and comb offset
    SRSs = [deepcopy(srs) for _ in 1:numUEs]
    for ue in 1:numUEs
        SRSs[ue].NumSRSPorts = numLayers[ue]
        SRSs[ue].SymbolStart = symD + symG + mod(ue - 1, symU)
        SRSs[ue].KBarTC = floor(Int64,(ue - 1) / symU)
    end

    return SRSs
end

